/**
 * @author caif
 * @fileoverview contact moudle
 */
;(function(){
    var tmpl ="<td width=10 class='toggle'><input type='checkbox'></td>"+
              "<td width=80>{{remarkName}}</td>"+
              "<td width=80>{{contactEmail}}</td>"+
              "<td width=80><a class='update btn btn-mini'>修改</a></td>"+
              "<td width=80><a class='destroy btn btn-mini'>删除</a></td>";
    
    var contactModel = Backbone.Model.extend({
        defaults: {
            id : null,

            userId: null,
            
            contactId : null,
            
            contactEmail : null,
            
            remarkName : null,
            
            remarkText : null,
            
            orderNum : null,
            
            createTime : null,
            
            updateTime : null
        },
        
        done : false,
        // Ensure that each contact created has 'title'.
        initialize: function() {
            
        },
        // Toggle the `done` state of this contact item.
        toggle: function() {
            this.done = !this.done;
        }, 
        // Remove this contact from *localStorage* and delete its view.
        clear: function( model ) {
            this.destroy( {
                url : "communicateBook/delete.json?id="+model.get("id")+"&contactId=" +model.get("contactId")
            });
        } ,
        
        destroy: function(options) {
            options = options ? _.clone(options) : {};
            var model = this;
            var success = options.success;
            var triggerDestroy = function() {
            	model.trigger('destroy', model, model.collection, options);
            };
            if (this.isNew()) {
	            triggerDestroy();
	            return false;
            }
            options.success = function(resp) {
	            if (options.wait) triggerDestroy();
	            if (success) {
	            	success(model, resp);
	            } else {
	            	model.trigger('sync', model, resp, options);
            	}
            };
            options.error = Backbone.wrapError(options.error, model, options);
            var xhr = (this.sync || Backbone.sync).call(this, 'read', this, options);
            if (!options.wait) triggerDestroy();
            return xhr;
        }
    });    
    
    var contactView = Backbone.View.extend({
        tagName: "tr",
        
        events: {
            "click .toggle" : "toggleDone",
            "click a.destroy" : "clear",
            "click a.update"  : "update"
        }, 
        
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('destroy', this.remove, this);
            
        }, 
        render: function() {
            this.$el.html( Mustache.to_html(tmpl, this.model.toJSON()));
            this.$el.toggleClass('done', this.model.done);
            return this;
        }, 
        toggleDone: function() {
            this.model.toggle();
            if( !this.model.done )
            {
                $("#toggle-all").prop("checked" , false);
            }
        }, 
        
        clear: function() {
            this.model.clear( this.model );
        } ,
        
        update : function(e){
            var that = this;
            $("#update_dlg").modal({
		        keyboard: true,
	    		show:true
		    });
            var sendReq = function(){
            	$.post("communicateBook/updateRemark.json" , {id : that.model.get("id"), remarkName : $("#contact_nick").val()} , function(){
                    that.model.set({remarkName : $("#contact_nick").val()});
                    $("#update_dlg").modal('hide');
                });
            };
            $("#update_dlg .btn-primary").unbind("click").click( function(e){
                sendReq();
            });
            $("#contact_nick").keydown(function(e){
            	if(e.which === 13){
            		sendReq();
            		return false;
            	}
            });
            
            $("#contact_nick").val(this.model.get("remarkName"));
        }
    });
    
    
    var contacts = Backbone.Collection.extend({
        model: contactModel,
        
        done: function() {
            return this.filter(function(model){ return model.done; });
        },
        // Filter down the list to only contact items that are still not finished.
        remaining: function() {
            return this.without.apply(this, this.done());
        }, 
        
        reset : function(models , options){
	        if( _.isObject( models ) )
	        {
	            models = models.items;
	        }
	        else
	        {
	            models  || (models = []);
	        }
	        
            options || (options = {});
            for (var i = 0, l = this.models.length; i < l; i++) {
              this._removeReference(this.models[i]);
            }
            this._reset();
            this.add(models, _.extend({silent: true}, options));
            if (!options.silent) this.trigger('reset', this, options);
            return this;
	    }
    });
    
    var contactList = new contacts;
    
    var appView = Backbone.View.extend({
        el : $("#linkMan"),
        events: {
            "click #clear-completed"  : "clearCompleted",
            "click #toggle-all"       : "toggleAllComplete",
            "click #add-contact"      : "addContact"
        }, 
        
        initialize: function() {
            this.allCheckbox = this.$("#toggle-all")[0];
            contactList.bind('add', this.addOne, this);
            contactList.bind('reset', this.addAll, this);
            contactList.bind('all', this.render, this);
            $("#linkman_tab").click(function(){
                $("#contact-body").empty();
                contactList.fetch({url : "communicateBook/list.json"});
            });
            $("#update_dlg , #add_dlg").on("show" , function( ){
				$(this).css({
		        	left: ($(window).width() - $(this).width())/2,
		        	top: 100
		    	});
			});
            $("#update_dlg , #add_dlg").draggable({
			        containment: 'body',
			        handle: '.modal-header'
			 });
        }, 
        
        render: function() {
            var done = contactList.done().length;
            var remaining = contactList.remaining().length;
            this.allCheckbox.checked = !remaining; 
        },
        // Add a single contact item to the list by creating a view for it, and
        // appending its element to the `<ul>`.
        addOne: function( model ) {
            $("#toggle-all").show();
            var view = new contactView({model: model}), col = view.model.collection;
            if( col.where({contactEmail: model.get("contactEmail")}).length > 1 )
            {
                col.remove( model );
                col.where({contactEmail: model.get("contactEmail")})[0].set({remarkName : model.get("remarkName")});
            }
            else
            {
                this.$("#contact-body").prepend(view.render().el).slideDown();
            }
        },
        // Add all items in the **contacts** collection at once.
        addAll: function( model ) {
            if( contactList.length )
            {
                contactList.each(this.addOne);
            }
            else
            {
                $("#toggle-all").hide();
            }
            
        }, 
        
        addContact : function(){
        	var accountName = $('#contact_email'),
        	remarkName = $("#contact_name");
        	$("#add_dlg").modal({
		        keyboard: true,
	    		show:true
		    });
            var sendReq = function(){
            	accountName.val($.trim(accountName.val()));
            	if(accountName.val() === ''){
            		accountName.focus().next("span").text('请输入联系人账号').show();
        			return false;
            	}
        		if(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(accountName.val()) || /^\d{11}$/.test(accountName.val())){
        			$.get("getUser.json",{accountName : accountName.val() } , function(data){
			            if(data.result !== null){
			            	remarkName.val($.trim(remarkName.val()));
				            contactList.create({
				            	contactId : data.result.id,
				            	remarkName : (remarkName.val() === '' ? accountName.val() : remarkName.val()) || accountName.val(),
				            	contactEmail : accountName.val()
			            	},{
			            		wait: true,
	                            url: "communicateBook/add.json",
	                            success : function(){
	                            	accountName.val('');
	            					remarkName.val('');
	            					accountName.next("span").hide();
	                                $("#add_dlg").modal('hide');
	                            },
	                            error: function(){
	                            	accountName.next("span").text('联系人添加失败').show();
	                            }
	                        });
			            }else{
			                accountName.next("span").text('该用户不存在').show();
			            }
		        	}, "json");
        		}else{
        			accountName.select().next("span").text('请输入正确的账号').show();
        			return false;
        		}
            };
            $("#add_dlg .btn-primary").unbind('click').click(function(){
                sendReq();
            });
            accountName.add(remarkName).unbind('keydown').keydown(function(e){
            	if(e.which === 13){
            		sendReq();
            		return false;
            	}
            });
        }
        ,
        clearCompleted: function() {
            _.each(contactList.done(), function(model){ 
                model.clear(model); 
            });
            return false;
        },
        
        toggleAllComplete: function () {
            var done = this.allCheckbox.checked;
            contactList.each(function (model) { 
                model.done = done; 
                if( done )
                {
                    $(".toggle input").prop("checked" , true); 
                }
                else
                {
                    $(".toggle input").prop("checked" , false); 
                }
            });
        } 
    });
    
    var app = new appView;
})();
